<template>
    <div class="some-tools">
        <div class="tool-left">
            <el-tree :data="data" node-key="id" :props="defaultProps" highlight-current default-expand-all @node-click="handleNodeClick"></el-tree>
        </div>
        <div class="tool-right">
            <div v-if="currentNode == '1'" class="blue">一些用来操作文本的小工具</div>

            <div v-else-if="currentNode == '1-1'">
                <input type="text" placeholder="输入需要转换的文本" @keypress.enter="changeULCase" v-model="textULToggle">
                <button @click="changeULCase">切换大小写</button>
                <h5>结果：</h5>
                <div class="result">{{uLCaseResult}}</div>
            </div>

            <div v-else-if="currentNode == '1-2'">
                <textarea placeholder="输入需要格式化的JSON" @keypress.enter="formatJSON" v-model="beforeFormatJson"></textarea>
                <button @click="formatJSON">格式化</button>
                <pre class="result pre-json">{{afterFormatJson}}</pre>
            </div>

            <div v-else-if="currentNode == '1-3'" style="position: relative; overflow: hidden;">
                <textarea id='textarea' v-model="contentsResult"></textarea>
                <textarea placeholder="输入需要生成目录的markdown文本（仅支持提取 ## 和 #### 二种级别的标题）" @keypress.enter="getContentsFromMarkdown" v-model="beforeContents"></textarea>
                <button @click="decodeMarkDown">提取标题</button> =>
                <button @click="getContentsFromMarkdown">生成目录</button>
                <pre class="result pre-json cursor" @click="copyContents">{{afterContents}}</pre>
            </div>

            <div v-else-if="currentNode == '2'" class="blue">一些用来处理颜色的小工具</div>

            <div class="colors" v-else-if="currentNode == '2-1'">
                <div v-for="(item,index) in colorList" :key="index">
                    <h5>{{item.name}}</h5>
                    <div class="color-group">
                        <div class="color-item" v-for="color in item.list" :key="color">
                            <div class="color" :style="{background: color}"></div>
                            <div class="value">{{color}}</div>
                        </div>
                    </div>
                </div>
            </div>

            <div style="position: relative; overflow: hidden;" v-else-if="currentNode == '2-2'">
                <input id='input' type="text" v-model="toolResult">
                <p>16进制颜色值要带“#”，rgb要用“,”隔开，如：#12e5cc、123,21,254</p>
                <input type="text" placeholder="输入颜色值" @keypress.enter="changeColorFormat" v-model="colorValue">
                <button @click="changeColorFormat">转换</button>
                <h5>结果：</h5>
                <div class="result cursor" @click="copyColorResult">{{colorFormatResult}}</div>
                <div :style="{width: '50px', height: '20px', marginTop: '10px', background: colorFormatResult}"></div>
            </div>

            <div class="tryColor" v-else-if="currentNode == '2-3'">
                <h3>优先使用输入框中的颜色值，仅支持7位16进制的颜色值</h3>
                <div class="backColor">
                    <span>选择或输入背景色：</span><input v-model="backColor" class="colorInput" type="color">
                    <input type="text" placeholder="输入背景色" v-model.lazy="backColor">
                </div>
                <div class="foreColor">
                    <span>选择或输入前景色：</span><input v-model="foreColor" class="colorInput" type="color">
                    <input type="text" placeholder="输入前景色" v-model.lazy="foreColor">
                </div>
                <div class="shadowColor">
                    <span>选择或输入阴影色：</span><input v-model="shadowColor" class="colorInput" type="color">
                    <input type="text" placeholder="输入阴影色" v-model.lazy="shadowColor">
                    <input type="range" class="marginLeft rangeInput" v-model="shadowRange" max="100"> {{shadowRange}}
                </div>
                <div class="backDiv" :style="{background: backColor}">
                    <div class="foreDiv" :style="{background: foreColor, boxShadow: '0 0 ' + shadowRange + 'px ' + shadowColor}"></div>
                </div>
            </div>

            <div v-else-if="currentNode == '3'" class="blue">快捷的处理设计图尺寸与实际不符时需要的比例换算</div>

            <div class="pixel" v-else-if="currentNode == '3-1'">
                当前环境下：
                <p>100vh = {{clientHeight}}px</p>
                <p>100wh = {{clientWidth}}px</p>
                <div>
                    <input type="text" v-model.lazy="pixel1"> px = <input type="text" v-model.lazy="visibleHeight1"> vh
                </div>
                <div class="marginTop">
                    <input type="text" v-model.lazy="pixel2"> px = <input type="text" v-model.lazy="visibleWidth1"> vw
                </div>
                <div class="marginTop">
                    <input type="text" v-model.lazy="pixel3"> px = <input type="text" v-model.lazy="relativePixel1"> rpx，其中设计稿基准宽度为 <input type="text" v-model.lazy="basicWidth1"> px
                </div>
            </div>

            <div v-else class="red">请先选择左侧的内容！！</div>
        </div>
    </div>
</template>

<script>
let ULCaseState = false //false 表示当前处于小写状态
export default {
    data() {
        return {
            toolResult: '',
            currentNode: null,

            textULToggle: '',
            uLCaseResult: '',

            beforeFormatJson: '',
            afterFormatJson: '',

            contentsResult: '',
            beforeContents: '',
            afterContents: '',

            colorValue: '',
            colorFormatResult: '',
            colorList: {},
            backColor: '#000000',
            foreColor: '#ffffff',
            shadowColor: '#ffffff',
            shadowRange: '50',

            clientHeight: document.body.clientHeight,
            clientWidth: document.body.clientWidth,
            pixel1: '',
            pixel2: '',
            pixel3: '',
            visibleHeight1: '',
            visibleWidth1: '',
            relativePixel1: '',
            basicWidth1: '750',

            data: [{
                label: '文本转换',
                id: '1',
                    children: [{
                        id: '1-1',
                        label: '英文大小写转换'
                    },{
                        id: '1-2',
                        label: 'JSON格式化'
                    },{
                        id: '1-3',
                        label: '掘金目录生成'
                    }]
                }, {
                label: '颜色工具',
                id: '2',
                    children: [{
                        id: '2-1',
                        label: '颜色组'
                    }, {
                        id: '2-2',
                        label: '单位转换'
                    },{
                        id: '2-3',
                        label: '试色'
                    }]
                }, {
                id: '3',
                label: '计算',
                children: [{
                    id: '3-1',
                    label: '尺寸换算'
                }]
            }],
            defaultProps: {
                children: 'children',
                label: 'label'
            }
        }
    },
    watch: {
        pixel1(val){
            this.visibleHeight1 = (100 / Number(this.clientHeight) * Number(val))
        },
        pixel2(val){
            this.visibleWidth1 = (100 / Number(this.clientWidth) * Number(val))
        },
        pixel3(val){
            this.relativePixel1 = (750 * Number(val) / Number(this.basicWidth1))
        },
        visibleHeight1(val){
            this.pixel1 = (Number(this.clientHeight) * Number(val) / 100)
        },
        visibleWidth1(val){
            this.pixel2 = (Number(this.clientWidth) * Number(val) / 100)
        },
        relativePixel1(val){
            this.pixel3 = (Number(val) * Number(this.basicWidth1) / 750)
        },
        basicWidth1(val){
            this.relativePixel1 = (750 * Number(this.pixel3) / Number(val))
        }
    },
    methods: {
        handleNodeClick(data) {
            this.currentNode = data.id
            if (data.id == '2-1') {
                this.getColorGroupData()
            }
            if (data.id == '3-1') {
                this.visibleHeight1 = '100'
                this.visibleWidth1 = '100'
                this.pixel3 = '100'
            }
        },
        changeULCase(){
            if (ULCaseState) {
                this.uLCaseResult = this.textULToggle.toLowerCase()
            }else{
                this.uLCaseResult = this.textULToggle.toUpperCase()
            }
            ULCaseState = !ULCaseState
        },
        formatJSON(){
            this.afterFormatJson = JSON.stringify(JSON.parse(this.beforeFormatJson), null, 2)
        },
        //解析 markdown 文本
        decodeMarkDown(){
            let res = ''
            this.beforeContents.split('\n').forEach(item => {
                if(item !== ''){
                    if (item.match(/##/g) && item.match(/##/g).length === 1) {
                        res = res + 
`## ${item.substring(3)}
`
                    }else if(item.indexOf('####') !== -1){
                        res = res + 
`#### ${item.substring(5)}
`
                    }
                }
            })
            this.beforeContents = res
        },
        getContentsFromMarkdown(){
            let res = `# 目录\n`
            // let text = '@@hahahah####shwuhduwhduw####qksoqi@@sjwidjwi####jwijdwi'
            let text = this.beforeContents.replace(/\s+/g,"").replace(/#{2}/g, '@@').replace(/@{4}/g, '####')
            console.log(text)
            let preCount = 0
            text.split('@@').slice(1).forEach(item => {
                let data = item
                res = res + 
`
- [${item.split('####')[0]}](#heading-${preCount + 1})`
                data.split('####').slice(1).forEach((child, index) => {
                        res = res + 
`
    - [${child}](#heading-${preCount + 1 + index + 1})`
                })
                preCount = preCount + item.split('####').length
            })
            this.afterContents = res
        },
        copyColorResult(){
            if (this.colorFormatResult == '') return
            this.toolResult = this.colorFormatResult
            this.$nextTick(() => {
                document.getElementById('input').select()
                let state = document.execCommand('copy')
                if (state) {
                    this.$notify({
                        title: '获取颜色值成功',
                        message: '已复制到剪切板',
                        type: 'success',
                        duration: 1500
                    })
                }else{
                    this.$notify({
                        title: '复制发生错误',
                        message: '请手动复制',
                        type: 'error',
                        duration: 0
                    })
                }
            })
        },
        copyContents(){
            if (this.afterContents === '') return
            this.contentsResult = this.afterContents
            this.$nextTick(() => {
                document.getElementById('textarea').select()
                let state = document.execCommand('copy')
                if (state) {
                    this.$notify({
                        title: '获取目录成功',
                        message: '已复制到剪切板',
                        type: 'success',
                        duration: 1500
                    })
                }else{
                    this.$notify({
                        title: '复制发生错误',
                        message: '请手动复制',
                        type: 'error',
                        duration: 0
                    })
                }
            })
        },
        changeColorFormat(){
            if(this.colorValue == '') return
            let r, g, b
            try{
                if (this.colorValue.indexOf('#') != -1) {
                    if (this.colorValue.length == 4) {
                        r = this.colorValue.trim().substring(1, 2)
                        g = this.colorValue.trim().substring(2, 3)
                        b = this.colorValue.trim().substring(3, 4)
                        r = r + r
                        g = g + g
                        b = b + b
                    }else{
                        r = this.colorValue.trim().substring(1, 3)
                        g = this.colorValue.trim().substring(3, 5)
                        b = this.colorValue.trim().substring(5, 7)
                    }
                    r = parseInt(r, 16)
                    g = parseInt(g, 16)
                    b = parseInt(b, 16)
                    this.colorFormatResult = 'rgb(' + [r, g, b].join() + ')'
                }else{
                    let colorArr = this.colorValue.trim().split(',')
                    colorArr = colorArr.map(item => {
                        let val = Number(item).toString(16)
                        if (val.length == 1) {
                            val = '0' + val
                        }
                        return val
                    })
                    this.colorFormatResult = '#' + colorArr.join('').toUpperCase()
                }
            }catch(error){
                console.log(error)
                this.colorFormatResult = '输入内容格式错误！'
            }
        },
        getColorGroupData(){
            this.$http({
                url: 'getColorGroup',
                method: 'post'
            }).then(res => {
                this.colorList = res.data.content
            })
        }
    },
}
</script>

<style lang="less" scoped>
@import '../css/common.less';
#input, #textarea{
    position: absolute;
    top: 0;
    right: -1000px;
    // border: none;
    z-index: -10
}
.some-tools{
    display: flex;
    justify-content: space-between;
    padding: 40px;
    height: calc(100vh - 80px);
    .tool-left{
        flex: 3;
        border: @green 4px dashed;
        margin-right: 40px;
        padding: 30px 0;
    }
    .tool-right{
        flex: 7;
        padding: 30px;
        border: @red 4px dashed;
        font-size: 20px;
        font-weight: bold;
        text-align: left;
        .result{
            font-weight: normal;
            font-size: 18px;
            &.pre-json{
                height: 44vh;
                width: 60vw;
                padding: 10px;
                box-sizing: border-box;
                border-radius: 5px;
                border: 1px solid @lightgrey;
                background: @lightgrey;
                overflow: scroll;
                // cursor: pointer;
            }
        }
        .colors{
            h5{
                margin: 10px auto;
            }
            .color-group{
                height: 33px;
                display: flex;
                .color-item{
                    flex: 1;
                    margin-right: 5px;
                    .color{
                        height: 60%;
                        border-radius: 5px;
                    }
                    .value{
                        font-size: 14px;
                        text-align: center;
                    }
                }
            }
        }
        .tryColor{
            font-size: 16px;
            .backColor, .foreColor, .shadowColor{
                display: flex;
                align-items: center;
                .colorInput{
                    border: none;
                    padding: 0;
                    height: 36px;
                    width: 70px;
                    cursor: pointer;
                    margin-right: 10px;
                }
                .rangeInput{
                    border: none;
                    padding: 0;
                    cursor: pointer;
                    margin-right: 10px;
                }
            }
            .backDiv{
                width: 70%;
                margin: 0 auto;
                padding-top: calc(20vh - 50px);
                box-sizing: border-box;
                border-radius: 10px;
                height: 40vh;
                margin-top: 10vh;
                .foreDiv{
                    width: 100px;
                    height: 100px;
                    border-radius: 50%;
                    margin: 0 auto;
                }
            }
        }
        .pixel{
            font-size: 16px;
            input{
                width: 50px;
            }
        }
    }
}
</style>
